package server.session.handler;

import server.session.UserSession;
import unit.data.Message;
import unit.request.Request;
import unit.request.SendMessageRequest;
import unit.response.IncomingMessage;
import unit.response.SendMessageRequestResponse;

import java.io.IOException;

/**
 * @author Yuri Denison
 * @since 07.08.11
 */
public class SendMessageRequestHandler implements RequestHandler {
    @Override
    public void handleRequest(Request request, UserSession userSession) {
        SendMessageRequest sendMessageRequest = (SendMessageRequest) request;
        boolean isDelivered = userSession.getCommunicator().send(
                sendMessageRequest.getReceiverId(),
                new IncomingMessage(userSession.getSession(), sendMessageRequest.getMessage())
        );
        SendMessageRequestResponse sendMessageRequestResponse = new SendMessageRequestResponse(
                request.getRequestID(),
                userSession.getSession(),
                sendMessageRequest.getReceiverId(),
                isDelivered
        );
        Message message = sendMessageRequest.getMessage();
        message.setDelivered(isDelivered);
        message.setTime(System.nanoTime());
        userSession.getDataStorage().addMessageToHistory(message);

        try {
            userSession.getConnector().send(sendMessageRequestResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
